<template>
	<view class="box">
		<view class="camera-preview" v-if="!showCamera">
			<!-- 显示默认图片 -->
			<image mode="widthFix" src="../../static/logo.png" style="width: 100%; height: 1000rpx"></image>
			<button class="takePhoto" type="primary" @tap="startPhoto">开 始 拍 照</button>
		</view>
		<view class="camera-now" v-else>
			<!-- <camera device-position="front" flash="off" @error="error" style="width: 100%; height: 300px;"></camera> -->
			<camera device-position="front" flash="off" binderror="error" style="width: 100%; height: 1000rpx;"></camera>
			<button class="takePhoto" type="primary" @tap="takePhoto">识 别</button>
		</view>
	</view>
</template>

<script>
	import {
		foodIdentity
	} from "@/api/food";

	export default {
		data() {
			return {
				// 展示相机
				showCamera: false,
				src: '',
				// 图像识别结果
				topFives: [{
					// 匹配度
					score: 0.5590515,
					// 热量
					calorie: "116",
					category: "米饭"
				}],
			}
		},
		onLoad() {},
		methods: {
			startPhoto() {
				this.showCamera = !this.showCamera;
			},
			takePhoto() {
				var that = this
				wx.authorize({
					scope: 'scope.camera',
					success(res) {
						console.log(res)
						if (res.errMsg == 'authorize:ok') {
							const cameraCtx = uni.createCameraContext();
							cameraCtx.takePhoto({
								quality: 'high',
								success: (res) => {
									that.src = res.tempImagePath;
									console.log(that.src);
									// 图片识别
									that.identity();
								},
								fail: (err) => {
									console.log('拍照失败:', err.detail);
								},
							});
						} else {
							wx.showToast({
								title: "授权失败，请重启小程序"
							})
							// 授权失败
							wx.redirectTo({
								url: "/pages/index"
							})
						}
					},
					fail(err) {
						console.log(err)
					}
				})
			},


			identity() {
				const FormData = require('@/utils/formData.js')
				this.loading = true;
				const formData = new FormData(); // 创建FormData实例
				// 手动拆解原始内容
				var OriginalFilename = this.src.split("/").pop()
				formData.appendFile("file", this.src, OriginalFilename);

				foodIdentity(formData.getData()) // 传递formData作为参数
					.then(response => {
						console.log('识别成功:', response.data);
						// 跳转结果界面
						var that = this
						// 存储json数据到
						wx.setStorageSync('result', response.data.data.topFives);
						wx.navigateTo({
								url: '/pages/dish/result/result?src=' +
									that.src
							}),
							this.loading = false;
					})
					.catch(error => {
						console.error('识别失败:', error);
						this.loading = false;
					});
			}

		}
	}
</script>

<style lang="scss">
	.box {
		.takePhoto {
			margin: 40rpx;
		}
	}
</style>